package utils

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go/v4"
	"golang.org/x/crypto/bcrypt"
	"log"
	"main/src/configs"
	"time"
)

type UserJWTInfo struct {
	Id        int       `json:"id"`
	Username  string    `json:"username"`
	IsBackUp  bool      `json:"is_back_up"`
	IsSuper   bool      `json:"is_super"`
	Password  string    `json:"password"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

func (u *UserJWTInfo) MarshalBinary() (data []byte, err error) {
	data, err = json.Marshal(u)
	log.Println("编码。。。:" + string(data))
	return data, err
}

func (u *UserJWTInfo) UnmarshalBinary(data []byte) (err error) {
	err = json.Unmarshal(data, u)
	log.Println("解析。。。" + string(data))
	return err
}

// CheckedPassword 密码校验
func (u *UserJWTInfo) CheckedPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err == nil {
		return true
	} else {
		return false
	}
}

type CustomClaims struct {
	UserJWTInfo
	jwt.StandardClaims
}

var Secret = []byte(configs.Config.Secret)

// GenToken 创建 Token
func GenToken(user *UserJWTInfo) (string, error) {
	claim := CustomClaims{
		*user,
		jwt.StandardClaims{
			ExpiresAt: jwt.At(time.Now().Add(time.Minute * time.Duration(configs.Config.TokenLiveTime))), //5分钟后过期
			Issuer:    "System",                                                                          //签发人
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	return token.SignedString(Secret)
}

// ParseToken 解析 token
func ParseToken(tokenStr string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenStr, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return Secret, nil
	})
	if err != nil {
		fmt.Println(" token parse err:", err)
		return nil, err
	}
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
